package com.voxel.sense.infomsg.module.publish;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.text.Editable;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.TextView;

import com.example.com.common.app.BaseActivity;
import com.example.com.common.utils.FileUtils;
import com.example.com.common.utils.IntentUtils;
import com.example.com.common.utils.L;
import com.example.com.common.utils.TimeUtils;
import com.example.com.common.utils.ToastUtil;
import com.example.com.common.view.dialog.DialogCallBack;
import com.example.com.common.view.dialog.DialogImpl;
import com.example.com.common.view.dialog.IDialog;
import com.voxel.sense.infomsg.R;
import com.voxel.sense.infomsg.data.FileImageInfo;
import com.voxel.sense.infomsg.utils.AppFileUtil;
import com.voxel.sense.infomsg.utils.FileProvider7;
import com.voxel.sense.infomsg.utils.OpenDocuIntentUtils;
import com.voxel.sense.infomsg.utils.manager.PlayVideoManager;
import com.voxel.sense.infomsg.view.MyGridView;
import com.voxel.sense.infomsg.view.titlebar.TextTitleBar;
import com.voxel.sense.infomsg.widget.CommonImagePagerActivity;
import com.voxel.sense.infomsg.widget.adapter.FileGalleryAdapter;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.OnItemClick;
import butterknife.OnTextChanged;
import cn.jzvd.Jzvd;
import cyy.example.com.facotry.Factory;
import cyy.example.com.facotry.constants.Constants;
import cyy.example.com.facotry.constants.IntentConstants;
import cyy.example.com.facotry.share.SPEngine;
import droidninja.filepicker.FilePickerBuilder;
import droidninja.filepicker.FilePickerConst;
import droidninja.filepicker.utils.Orientation;

//import com.mabeijianxi.smallvideorecord2.MediaRecorderActivity;

/**
 * 填报上传
 */
public class FeedbackUpActivity extends BaseActivity {

    @BindView(R.id.gridview_image)
    MyGridView gridview_image; //图片grid
    @BindView(R.id.gridview_doc)
    MyGridView gridview_doc;//文档grid
    @BindView(R.id.tv_video_text_desc)
    TextView tv_video_text_desc;//视频描述的item
    @BindView(R.id.gridview_video)
    MyGridView gridview_video;//视频grid
    @BindView(R.id.btn_submit)
    Button btn_submit;//提交按钮
    @BindView(R.id.et_advice)
    EditText et_advice;
    @BindView(R.id.tv_content_count)
    TextView tv_content_count;//编辑框输入限制提示
    @BindView(R.id.titlebar)
    TextTitleBar titlebar;

    private FileGalleryAdapter mImageAdapter;//图片展示的适配器
    private FileGalleryAdapter mDocuAdapter;//文件展示的适配器
    private FileGalleryAdapter mVideoAdapter;//文件展示的适配器

    private ArrayList<String> mSelectImagePath;//选择图片返回的path
    private ArrayList<String> mSelectDocuPath;//选择图片返回的path
    private ArrayList<String> mSelectVideoPath;//选择图片返回的path
    private long mVideoUploadMaxSize;
    private File mTakePhotoFile;
    private boolean mIsSelecPic;

    public static void show(Context context) {
        context.startActivity(new Intent(context, FeedbackUpActivity.class));
    }


    @Override
    protected int getContentLayoutId() {
        return R.layout.activity_feedback_up;
    }


    @Override
    protected void onPause() {
        super.onPause();
        Jzvd.resetAllVideos();
    }

    @Override
    protected void initData() {
        super.initData();
        //初始化视频拍摄的配置
        PlayVideoManager.initSmallVideo();
        titlebar.setTitleText("填报上传");
        btn_submit.setText("提交");
        mVideoUploadMaxSize = SPEngine.getSPEngine().getVideoUploadMaxSize();
        L.d("mVideoUploadMaxSize:" + mVideoUploadMaxSize);
        if (mVideoUploadMaxSize != 0) {
            tv_video_text_desc.setText(String.format(getString(R.string.up_video_text_desc), mVideoUploadMaxSize + "M"));
        } else {
            mVideoUploadMaxSize = 20;
            tv_video_text_desc.setText(String.format(getString(R.string.up_video_text_desc), mVideoUploadMaxSize + "M"));
        }

        mSelectImagePath = new ArrayList<>();
        mSelectDocuPath = new ArrayList<>();
        mSelectVideoPath = new ArrayList<>();
        ArrayList<FileImageInfo> lstImageData = new ArrayList<>();
        ArrayList<FileImageInfo> listDocuData = new ArrayList<>();
        ArrayList<FileImageInfo> listVideoData = new ArrayList<>();

        //添加一个头显示添加图片的样式
        lstImageData.add(new FileImageInfo(Constants.ADD_FILE, Constants.ADD_FILE));
        listDocuData.add(new FileImageInfo(Constants.ADD_FILE, Constants.ADD_FILE));
        listVideoData.add(new FileImageInfo(Constants.ADD_FILE, Constants.ADD_FILE));

        //初始化图片选择模块
        mImageAdapter = new FileGalleryAdapter(this, lstImageData);
        gridview_image.setAdapter(mImageAdapter);

        //初始化文档选择模块
        mDocuAdapter = new FileGalleryAdapter(this, listDocuData);
        mDocuAdapter.setFile_type(Constants.file_docu);
        gridview_doc.setAdapter(mDocuAdapter);

        //初始化视频选择模块
        mVideoAdapter = new FileGalleryAdapter(this, listVideoData);
        mVideoAdapter.setFile_type(Constants.file_vedio);
        mVideoAdapter.setMax_num(1);
        gridview_video.setAdapter(mVideoAdapter);
    }

    @OnTextChanged(value = R.id.et_advice, callback = OnTextChanged.Callback.AFTER_TEXT_CHANGED)
    void afterTextChanged(Editable s) {
        String str = (180 - s.length() >= 1) ? (180 - s.length()) + "" : "输入字数已达最大限制";
        tv_content_count.setText(str);
    }

    @Override
    protected void initEven() {
        super.initEven();
        btn_submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                submit();
            }
        });
    }

    private void submit() {
        ToastUtil.showToastLong(Factory.app(), "研发中，暂不能提交");
    }

    /**
     * 列表点击事件
     */
    @OnItemClick({R.id.gridview_image, R.id.gridview_doc, R.id.gridview_video})
    public void gridItemClick(GridView view, View childrenView, int position, long id) {
        switch (view.getId()) {
            case R.id.gridview_image://图片item点击事件
                pickClickEvent(position);
                break;
            case R.id.gridview_doc://文档item点击事件
                docuClickEvent(position);
                break;
            case R.id.gridview_video://视频item点击事件
                videoClickEvent(position);
                break;

        }
    }


    private void videoClickEvent(final int position) {
        if (position == mVideoAdapter.getCount() - 1) {
            //点击最后一个，则是添加视频
            List<String> list = new ArrayList<>();
            list.add("拍摄");
            list.add("从相册选中");
            DialogImpl.getInstance().showItemDialog(this, "", list, new DialogCallBack() {
                @Override
                public void onClick(int what) {
                    if (what == 0) {
                        PlayVideoManager.playVideio(FeedbackUpActivity.this);
                        //拍摄
                    } else {
                        addPicOrVideo(false, mSelectVideoPath);

                    }
                }
            });
        } else {
            //播放图片
            IDialog.getInstance().showChooseDialog(this, "", "是否播放视频", new DialogCallBack() {
                @Override
                public void onClick(int what) {
                    if (IDialog.YES == what) {
//                        FullScreenJPlayerActivity.show(MissionActionUpActivity.this, mSelectVideoPath.get(position));
                        Jzvd.startFullscreenDirectly(FeedbackUpActivity.this, Jzvd.class, mSelectVideoPath.get(position), "");
                    }
                }
            });
        }
    }


    private void pickClickEvent(int position) {
        if (position == mImageAdapter.getCount() - 1) {
            //点击最后一个，则是添加图片
            List<String> list = new ArrayList<>();
            list.add("拍摄");
            list.add("从相册选中");
            DialogImpl.getInstance().showItemDialog(this, "", list, new DialogCallBack() {
                @Override
                public void onClick(int what) {
                    if (what == 0) {
                        //拍照
                        takePhoto();
                    } else {
                        addPicOrVideo(true, mSelectImagePath);
                    }
                }
            });
        } else {
            //查看图片
            CommonImagePagerActivity.showImages(FeedbackUpActivity.this, mSelectImagePath, position);
        }
    }

    private void docuClickEvent(int position) {
        if (position == mDocuAdapter.getCount() - 1) {
            //点击最后一个，则是添加图片
            addDoc();
        } else {
            String type = "text/plain";//默认文本类型
            String file = mSelectDocuPath.get(position);
            String fileExtension = FileUtils.getFileExtension(file);

            if (Constants.EXTENSION_DOC.equals(fileExtension) || Constants.EXTENSION_DOCX.equals(fileExtension)) {
                //doc文档
                type = "application/msword";
            } else if (Constants.EXTENSION_XLS.equals(fileExtension) || Constants.EXTENSION_XLSX.equals(fileExtension)) {
                //xls文档
                type = "application/vnd.ms-excel";
            } else if (Constants.EXTENSION_PDF.equals(fileExtension)) {
                //pdf文档
                type = "application/pdf";
            } else if (Constants.EXTENSION_PPT.equals(fileExtension) || Constants.EXTENSION_PPTX.equals(fileExtension)) {
                //ppt文档
                type = "application/vnd.ms-powerpoint";
            }
            OpenDocuIntentUtils.DocuItent(this, new File(file), type, fileExtension);
        }
    }


    private void takePhoto() {
        mTakePhotoFile = new File(AppFileUtil.getPhoneImageDir(),
                TimeUtils.getNowString(new SimpleDateFormat("yyyy-MM-ddHHmmss", Locale.getDefault())) + ".jpg");

        if (FileUtils.isFileExists(mTakePhotoFile)) {
            L.d("-------拍照的文件存在-------");
        } else {

            L.d("-------拍照的文件不存在-------");
        }

        Uri uriForFile = FileProvider7.getUriForFile(mTakePhotoFile);
        Intent intent = IntentUtils.getCaptureIntent(uriForFile);
        startActivityForResult(intent, IntentConstants.REQUEST_CODE_TAKE_PHOTO);
    }


    /**
     * 调出图片或视频的选择器
     *
     * @param isPic ture时是选择图片，flase是视频
     */
    private void addPicOrVideo(boolean isPic, ArrayList<String> list) {
        mIsSelecPic = isPic;
        FilePickerBuilder.getInstance().setMaxCount(Constants.UPLOAD_FILE_MAX_COUNT)
                .setSelectedFiles(list)
                .setActivityTheme(R.style.FilePickerTheme)
                .enableImagePicker(isPic)
                .enableVideoPicker(!isPic)//是否能视频图片
                .enableCameraSupport(isPic)//是否有照相item
                .showGifs(false)//是否显示gif图
                .showFolderView(false)//是否显示文件夹
                .enableSelectAll(true)//是否选中全部，这个选中只有没有选中数量的情况下才能使用
                .setCameraPlaceholder(R.mipmap.custom_camera)//相机图片
                .withOrientation(Orientation.UNSPECIFIED)
                .pickPhoto(this);//显示文件
    }

    /**
     * 拉起文档选择器
     */
    private void addDoc() {
        FilePickerBuilder.getInstance().setMaxCount(Constants.UPLOAD_FILE_MAX_COUNT)
                .setSelectedFiles(mSelectDocuPath)
                .setActivityTheme(R.style.FilePickerTheme)
                .showFolderView(false)//是否显示文件夹
                .enableSelectAll(true)//是否选中全部，这个选中只有没有选中数量的情况下才能使用
                .setCameraPlaceholder(R.mipmap.custom_camera)//相机图片
                .withOrientation(Orientation.UNSPECIFIED)
                .pickFile(this);
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case FilePickerConst.REQUEST_CODE_PHOTO://图片及选择回调
                    if (resultCode == Activity.RESULT_OK && data != null) {
                        getSelectPicOrVideoResult(data);
                    }
                    break;
                case FilePickerConst.REQUEST_CODE_DOC: //文档选择回调
                    if (resultCode == Activity.RESULT_OK && data != null) {
                        getSelectDocuResult(data);
                    }
                    break;
                case IntentConstants.REQUEST_CODE_TAKE_PHOTO://拍照回调
                    getTakePhoneResult();
                    break;
//                case MediaRecorderActivity.start_request://拍摄回调
//                    getTakeVideoResult(data);
//                    break;
            }
        }
    }

    private void getSelectPicOrVideoResult(Intent data) {
        if (mIsSelecPic) {//图片类型
            //清空集合，重新加载数据
            mSelectImagePath.clear();
            mSelectImagePath.addAll(data.getStringArrayListExtra(FilePickerConst.KEY_SELECTED_MEDIA));
            List<FileImageInfo> list = mImageAdapter.getList();
            //移除数据，只保留添加的item
            while (list != null && list.size() > 1) {
                list.remove(0);
            }
            for (int i = 0; i < mSelectImagePath.size(); i++) {
                File file = new File(mSelectImagePath.get(i));
                if (file.exists() && list != null && list.size() > 0) {
                    FileImageInfo fileImageInfo = new FileImageInfo(file.getName(), file.getPath());
                    list.add(list.size() - 1, fileImageInfo);
                }
            }
            mImageAdapter.notifyDataSetChanged();
        } else {
            //视频类型
            mSelectVideoPath.clear();
            mSelectVideoPath.addAll(data.getStringArrayListExtra(FilePickerConst.KEY_SELECTED_MEDIA));
            List<FileImageInfo> list = mVideoAdapter.getList();
            while (list != null && list.size() > 1) {
                list.remove(0);
            }
            for (int i = 0; i < mSelectVideoPath.size(); i++) {
                File file = new File(mSelectVideoPath.get(i));
                if (file.exists() && list != null && list.size() > 0) {
                    FileImageInfo fileImageInfo = new FileImageInfo(file.getName(), file.getPath());
                    list.add(list.size() - 1, fileImageInfo);
                }
            }
            mVideoAdapter.notifyDataSetChanged();
        }
    }

    private void getSelectDocuResult(Intent data) {
        mSelectDocuPath.clear();
        mSelectDocuPath.addAll(data.getStringArrayListExtra(FilePickerConst.KEY_SELECTED_DOCS));
        //移除数据，只保留添加的item
        List<FileImageInfo> list = mDocuAdapter.getList();
        while (list != null && list.size() > 1) {
            list.remove(0);
        }
        for (int i = 0; i < mSelectDocuPath.size(); i++) {
            File file = new File(mSelectDocuPath.get(i));
            if (file.exists() && list != null && list.size() > 0) {
                FileImageInfo fileImageInfo = new FileImageInfo(file.getName(), file.getPath());
                list.add(list.size() - 1, fileImageInfo);
            }
        }
        mDocuAdapter.notifyDataSetChanged();
    }

    private void getTakePhoneResult() {
        if (FileUtils.isFileExists(mTakePhotoFile)) {
            Intent borad = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
            borad.setData(Uri.fromFile(mTakePhotoFile));
            sendBroadcast(borad);
            //拿到拍照回来的图片 路径，将其插入选择的照片集合最后一个位置中。
            if (mSelectImagePath.size() > 0) {
                mSelectImagePath.add(mSelectImagePath.size() - 1, mTakePhotoFile.getPath());
            } else {
                mSelectImagePath.add(mTakePhotoFile.getPath());
            }
            FileImageInfo fileImageInfo = new FileImageInfo(mTakePhotoFile.getName(), mTakePhotoFile.getPath());
            List<FileImageInfo> list = mImageAdapter.getList();
            list.add(list.size() - 1, fileImageInfo);
            mImageAdapter.notifyDataSetChanged();
        } else {
            ToastUtil.showToastLong(Factory.app(), "获取拍摄照片失败");
        }
    }

    private void getTakeVideoResult(Intent data) {
//        String VideoUrl = data.getStringExtra(MediaRecorderActivity.VIDEO_URI);
//        Log.d("video-info", "VIDEO_URI:" + data.getStringExtra(MediaRecorderActivity.VIDEO_URI));
//        Log.d("video-info", "OUTPUT_DIRECTORY:" + data.getStringExtra(MediaRecorderActivity.OUTPUT_DIRECTORY));
//        Log.d("video-info", "VIDEO_SCREENSHOT:" + data.getStringExtra(MediaRecorderActivity.VIDEO_SCREENSHOT));
//        //视频类型
//        if (!TextUtils.isEmpty(VideoUrl) && FileUtils.isFileExists(VideoUrl)) {
//            mSelectVideoPath.clear();
//            mSelectVideoPath.add(VideoUrl);
//            List<FileImageInfo> list = mVideoAdapter.getList();
//            while (list != null && list.size() > 1) {
//                list.remove(0);
//            }
//            for (int i = 0; i < mSelectVideoPath.size(); i++) {
//                File file = new File(mSelectVideoPath.get(i));
//                if (file.exists() && list != null && list.size() > 0) {
//                    FileImageInfo fileImageInfo = new FileImageInfo(file.getName(), file.getPath());
//                    list.add(list.size() - 1, fileImageInfo);
//                }
//            }
//            mVideoAdapter.notifyDataSetChanged();
//        }
    }

    @Override
    public void onBackPressed() {
        if (Jzvd.backPress()) {
            return;
        }
        super.onBackPressed();

    }
}
